var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');

var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var webRouter = require('./routes/web');

var session = require('express-session');

var app = express();

// 设置允许跨域访问
app.all("*",function(req,res,next){
  res.header("Access-Control-Allow-Origin","*");
  res.header("Access-Control-Allow-Headers","content-type");
  res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
  req.method.toLowerCase() == 'options' ? res.send(200) : next();
});

// 使用 session 中间件
app.use(session({
	secret :  'secret', // 对session id 相关的cookie 进行签名
	resave : true,
	saveUninitialized: false, // 是否保存未初始化的会话
	cookie : {
		maxAge : 1000 * 60 * 60 * 6, // 设置 session 的有效时间，单位毫秒
	}
}));


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.use('/public',express.static('./public/'));
app.set('view engine', 'jade');


// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
app.engine('html',require('express-art-template'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use('/web', webRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
